'use client';

import { useEffect, useState } from 'react';
import { Card, Typography, Descriptions, Button, Message, Spin } from '@arco-design/web-react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { Customer } from '@/types';
import { customerApi } from '@/services/api';

const { Title } = Typography;

export default function ProfilePage() {
  const { user, userType, isAuthenticated } = useAuth();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [customerData, setCustomerData] = useState<Customer | null>(null);

  console.log('ProfilePage 渲染 - 认证状态:', { isAuthenticated, userType });

  useEffect(() => {
    console.log('ProfilePage useEffect 执行 - 认证状态:', { isAuthenticated, userType });

    // 如果未登录或不是客户，重定向到登录页
    if (!isAuthenticated) {
      router.push('/login');
      return;
    }

    if (userType !== 'customer') {
      router.push('/');
      return;
    }

    // 获取最新的客户信息
    const fetchCustomerData = async () => {
      // 确保用户已登录且是客户类型
      if (!isAuthenticated || userType !== 'customer') return;

      setLoading(true);
      try {
        // 修改：调用 getCurrentUser 接口
        const response = await customerApi.getCurrentUser();
        console.log('获取当前用户信息响应:', response);

        // 修改：根据 ApiResponse 结构判断成功
        if (response.code === 200 && response.data) {
          setCustomerData(response.data);
        } else {
          // Message.error(response.message || '获取用户信息失败');
          // 如果获取失败且不是未授权（401），可能需要进一步处理，例如跳转回首页或登录页
          // if (response.code !== 401) {
          //   router.push('/'); 
          // }
        }
      } catch (error) {
        console.error('获取用户信息错误:', error);
        // Message.error('获取用户信息时发生错误');
      } finally {
        setLoading(false);
      }
    };

    fetchCustomerData();

    // 依赖项更新：不再依赖 user 对象中的 customerID
  }, [isAuthenticated, userType, router]);

  if (!isAuthenticated || userType !== 'customer') {
    return null;
  }

  return (
    <div className="max-w-3xl mx-auto py-8">
      <Card className="shadow-md">
        <Title heading={3} className="mb-6">个人信息</Title>

        {loading ? (
          <div className="flex justify-center py-8">
            <Spin />
          </div>
        ) : (
          <Descriptions
            column={1}
            title="基本信息"
            data={[
              {
                label: '用户名',
                value: customerData?.username
              },
              {
                label: '姓名',
                value: customerData?.name
              },
              {
                label: '身份证号',
                value: customerData?.idNumber
              },
              {
                label: '手机号',
                value: customerData?.phone
              }
            ]}
            labelStyle={{ fontWeight: 'bold', width: '100px' }}
          />
        )}

        <div className="flex justify-center mt-6">
          <Button type="primary" onClick={() => router.push('/bookings')}>
            查看我的预订
          </Button>
        </div>
      </Card>
    </div>
  );
}